import router from '@/router'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import ACCESS_ENUM from '@/access/accessEnum.ts'
import checkAccess from '@/access/checkAccess.ts'

// 是否为首次获取登录用户
let firstFetchLoginUser = true

router.beforeEach(async (to, from, next) => {
  const loginUserStore = useLoginUserStore()
  let loginUser = loginUserStore.loginUser

  // 确保页面刷新时，首次加载时，能等待后端返回用户信息后再校验权限
  if (firstFetchLoginUser) {
    await loginUserStore.fetchLoginUser()
    loginUser = loginUserStore.loginUser
    firstFetchLoginUser = false
  }
  // //之前没登陆过进行自动登陆
  // if (loginUser.userRole !== ACCESS_ENUM.NOT_LOGIN) {
  //   await loginUserStore.fetchLoginUser()
  // }
  //获取要跳转到的页面的权限
  const needAccess = (to.meta?.access as any) ?? ACCESS_ENUM.NOT_LOGIN
  //要跳转的页面必须要登陆
  if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
    //没登陆跳转到登陆页面
    if (!loginUser || loginUser.userRole === ACCESS_ENUM.NOT_LOGIN) {
      next(`/user/login`)
      return
    }
    //如果登陆后权限不足，跳转到无权限页面
    if (!checkAccess(loginUser, needAccess)) {
      next(`/noAuth`)
      return
    }
  }
  next()
})
